package code1.hash;

import java.util.HashMap;
import java.util.Map;

/**
 * 原题链接：https://leetcode.cn/problems/ransom-note/
 */
public class P383 {

    //利用map
    public boolean canConstruct(String ransomNote, String magazine) {
        Map<Character,Integer> map=new HashMap<>();         //key为magazine中出现的字符,value为其出现的次数
        for(int i=0;i<magazine.length();i++){
            if(map.get(magazine.charAt(i))==null){
                map.put(magazine.charAt(i),1);
            }else{
                map.put(magazine.charAt(i), map.get(magazine.charAt(i))+1);
            }
        }
        for(int i=0;i<ransomNote.length();i++){
            char ch = ransomNote.charAt(i);
            if(map.get(ch)==null || map.get(ch)==0){
                return false;
            }else {
                map.put(ch,map.get(ch)-1);
            }
        }
        return true;
    }

    //利用数组
    public boolean canConstruct2(String ransomNote, String magazine) {
        int[] count=new int[26];
        for(int i=0;i<magazine.length();i++){
            count[magazine.charAt(i)-'a']++;
        }
        for(int i=0;i<ransomNote.length();i++){
            if(count[ransomNote.charAt(i)-'a']>0){
                count[ransomNote.charAt(i)-'a']--;
            }else{
                return false;
            }
        }
        return true;
    }
}
